package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"practice-hub/cache"
	"practice-hub/model"
	"strconv"
	"time"
)

func UserLists(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var user []model.User
	redis_key := "data"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(&user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": user})
	return
}
